﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;


namespace WD.Web.MVC.Common
{
    public static class StaticSMS
    {
        //验证签名
        static string SignName = "三众装饰";
        //链接地址
        private static string url = "http://gw.api.taobao.com/router/rest";

        private static string templateLogin = "SMS_134830122";//登录短信模版

        private static string templateRegister = "SMS_128560044";//注册短信模版

        private static string templateTiXian = "SMS_128560042";//申请提现模板

        private static string templatePwd = "SMS_128560043";//修改登录密码模板

        private static string templateTXPwd = "SMS_128560042";//修改提现密码模板

        private static string templateForgetPwd = "SMS_128560043";//找回密码模板  

        private static string product = "Dysmsapi";//短信API产品名称
        private static string domain = "dysmsapi.aliyuncs.com";//短信API产品域名
        private static string accessId = "LTAI90V6RJ738i95";//你的accessKeyId
        private static string accessSecret = "UpU0spAUAU6Cm8fACg0T9NytGFRxIJ";//你的accessKeySecret
        private static string regionIdForPop = "cn-hangzhou";


        /// <summary>
        /// 发送找回密码验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static ModelSMS sendForgetCode(string phone)
        {
            ModelSMS model = SendSMS(phone, templateForgetPwd);
            return model;
        }

        /// <summary>
        /// 发送修改提现密码验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static ModelSMS SendTXPwdCode(string phone)
        {
            ModelSMS model = SendSMS(phone, templateTXPwd);
            return model;
        }

        /// <summary>
        /// 发送修改登录密码验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static ModelSMS SendPwdCode(string phone)
        {
            ModelSMS model = SendSMS(phone, templatePwd);
            return model;
        }

        /// <summary>
        /// 发送申请提现验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static ModelSMS SendTiXianCode(string phone)
        {
            ModelSMS model = SendSMS(phone, templateTiXian);
            return model;
        }

        /// <summary>
        /// 发送注册验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static ModelSMS SendRegister(string phone)
        {
            ModelSMS model = SendSMS(phone, templateRegister);
            return model;
        }
        /// <summary>
        /// 发送登录验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static ModelSMS SendLogin(string phone)
        {
            ModelSMS model = SendSMS(phone, templateLogin);
            return model;
        }

        private static ModelSMS SendSMS(string phone, string strTemp)
        {
            ModelSMS model = new ModelSMS();

            IClientProfile profile = DefaultProfile.GetProfile(regionIdForPop, accessId, accessSecret);
            DefaultProfile.AddEndpoint(regionIdForPop, regionIdForPop, product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            try
            {
                Random random = new Random();
                int codeSms = random.Next(100000, 999999);

                //request.SignName = "上云预发测试";//"管理控制台中配置的短信签名（状态必须是验证通过）"
                //request.TemplateCode = "SMS_71130001";//管理控制台中配置的审核通过的短信模板的模板CODE（状态必须是验证通过）"
                //request.RecNum = "13567939485";//"接收号码，多个号码可以逗号分隔"
                //request.ParamString = "{\"name\":\"123\"}";//短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
                //SingleSendSmsResponse httpResponse = client.GetAcsResponse(request);
                request.PhoneNumbers = phone;
                request.SignName = SignName;
                request.TemplateCode = strTemp;
                request.TemplateParam = "{\"code\":\"" + codeSms + "\"}";
                //request.OutId = "xxxxxxxx";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);

                model.phone = phone;
                model.code = codeSms;
                model.isSuccess = sendSmsResponse.Code == "OK";
                if (!model.isSuccess)
                {
                    if (sendSmsResponse.Code == "isv.MOBILE_NUMBER_ILLEGAL")
                    {
                        model.ErrorMessage = "非法手机号";
                    }
                    else if (sendSmsResponse.Code == "isv.AMOUNT_NOT_ENOUGH")
                    {
                        model.ErrorMessage = "账户余额不足";
                    }
                    else if (sendSmsResponse.Code == "isv.MOBILE_COUNT_OVER_LIMIT")
                    {
                        model.ErrorMessage = "手机号码数量超过限制";
                    }
                    else if (sendSmsResponse.Code == "isv.BUSINESS_LIMIT_CONTROL")
                    {
                        model.ErrorMessage = "发送频繁，稍后再试";
                    }
                    else
                    {
                        model.ErrorMessage = "其他未知错误：" + sendSmsResponse.Code;
                    }
                }
            }
            catch (ServerException e)
            {
                System.Console.WriteLine("ServerException");
            }
            catch (ClientException e)
            {
                System.Console.WriteLine("ClientException");
            }
            return model;
        }


        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="strTemplate"></param>
        /// <returns></returns>
        //private static ModelSMS SendSMS(string phone, string strTemplate)
        //{
        //    Random random = new Random();
        //    int codeSms = random.Next(100000, 999999);

        //    ITopClient client = new DefaultTopClient(url, appkey, secret);
        //    AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        //    req.Extend = "123456";
        //    req.SmsType = "normal";
        //    req.SmsFreeSignName = SignName;
        //    req.SmsParam = "{\"code\":\"" + codeSms + "\",\"product\":\"众享经济链\"}";
        //    req.RecNum = phone;
        //    req.SmsTemplateCode = strTemplate;

        //    AlibabaAliqinFcSmsNumSendResponse rsp = client.Execute(req);
        //    Console.WriteLine(rsp.Body);
        //    XmlDocument xml = new XmlDocument();
        //    xml.LoadXml(rsp.Body);

        //    ModelSMS model = new ModelSMS();
        //    model.code = codeSms;
        //    XmlNodeList xmlNodeList = xml.DocumentElement.GetElementsByTagName("success");
        //    bool result = false;
        //    if (xmlNodeList.Count > 0)
        //    {
        //        result = Convert.ToBoolean(xmlNodeList.Item(0).InnerText);
        //        model.isSuccess = result;
        //    }
        //    else
        //    {
        //        XmlNodeList xmlNodelistErrCode = xml.DocumentElement.GetElementsByTagName("sub_code");
        //        if (xmlNodelistErrCode.Count > 0)
        //        {
        //            var str = xmlNodelistErrCode.Item(0).InnerText;
        //            if (str == "isv.BUSINESS_LIMIT_CONTROL")
        //            {
        //                model.ErrorMessage = "发送短信次数太频繁";
        //                return model;
        //            }
        //        }


        //        XmlNodeList xmlNodelistErr = xml.DocumentElement.GetElementsByTagName("sub_msg");
        //        if (xmlNodelistErr.Count > 0)
        //        {
        //            model.ErrorMessage = xmlNodelistErr.Item(0).InnerText;
        //        }
        //    }
        //    return model;
        //}

    }


    public class ModelSMS
    {
        /// <summary>
        /// 发送的验证码
        /// </summary>
        public int code { get; set; }

        /// <summary>
        /// 发送的手机号
        /// </summary>
        public string phone { get; set; }

        /// <summary>
        /// TRUE:发送成功  FALSE:失败
        /// </summary>
        public bool isSuccess { get; set; }

        /// <summary>
        /// 失败返回的消息
        /// </summary>
        public string ErrorMessage { get; set; }
    }
}